#include "informationeditwindow.h"
#include "ui_informationeditwindow.h"

InformationEditWindow::InformationEditWindow(QTcpSocket * clientSocket,QWidget *parent)
    : QWidget(parent)
    , ui(new Ui::InformationEditWindow)
    ,clientSocket(clientSocket)
{
    ui->setupUi(this);
    QPixmap pixmap("../../../resource/1.jpg");
    // 创建一个QPalette实例
    QPalette palette;
    palette.setBrush(QPalette::Window, pixmap);
    // 设置窗口的调色板
    this->setPalette(palette);
    // 设置窗口标题
    this->setWindowTitle("信息修改");
}

void InformationEditWindow::on_PushButton_clicked(){
    // get select Doctor ID
    QString newUserName = ui->UserNameEdit->text();
    QString newUserPassword = ui->PassWordEdit->text();
    QString doctorsIdStr = QString::number(currentUserID);

    QString queryStr = "UPDATE Doctors SET password = '"+newUserPassword+"' WHERE doctor_id = "+doctorsIdStr+";";

    clientSocket->write(queryStr.toUtf8());
    clientSocket->waitForBytesWritten(1000); // 等待数据写入完成，超时时间为1秒

    if (clientSocket->waitForReadyRead(3000)) { // 等待数据接收，超时时间为3秒
        // 接收数据
        QByteArray data = clientSocket->readAll();

        // 将数据转换为字符串
        QString receivedData = QString::fromUtf8(data);

        // 检查接收到的数据是否为"failed"
        if (receivedData == "failed") {
            ;
        } else {
            QMessageBox::warning(this,tr("Error"),receivedData);
        }
    } else {
        // 如果超时未接收到数据
        QMessageBox::warning(this, tr("Error"), tr("No response from the server."));
    }

    queryStr = "UPDATE Doctors SET password = '"+newUserName+"' WHERE doctor_id = "+doctorsIdStr+";";
    clientSocket->write(queryStr.toUtf8());
    clientSocket->waitForBytesWritten(1000); // 等待数据写入完成，超时时间为1秒

    if (clientSocket->waitForReadyRead(3000)) { // 等待数据接收，超时时间为3秒
        // 接收数据
        QByteArray data = clientSocket->readAll();

        // 将数据转换为字符串
        QString receivedData = QString::fromUtf8(data);

        // 检查接收到的数据是否为"failed"
        if (receivedData == "failed") {
            ;
        } else {
            QMessageBox::warning(this,tr("Error"),receivedData);
        }
    } else {
        // 如果超时未接收到数据
        QMessageBox::warning(this, tr("Error"), tr("No response from the server."));
    }
    currentUserName = newUserName;
    QMessageBox::information(this, tr("Success"), tr("Modification successful!"));
}

void InformationEditWindow::on_BackButton_clicked(){
    emit back();
}

InformationEditWindow::~InformationEditWindow()
{
    delete ui;
}
